﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Description;
using System.Text;

namespace Spike.ServiceFramework.ServiceModel
{
    public class FrameworkHostFactory : ServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            return new FrameworkServiceHost(serviceType, baseAddresses);
        }
    }

    public class FrameworkServiceHost : ServiceHost
    {
        public ServiceBehaviorExtension ServiceBehaviorExtension { get; set; }

        public FrameworkServiceHost(Type t, params Uri[] baseAddresses) : base(t, baseAddresses)
        {
        }

        public FrameworkServiceHost(object singletonInstance, params Uri[] baseAddresses) : base(singletonInstance, baseAddresses)
        {
        }

        public FrameworkServiceHost() : base()
        {
        }

        protected override void OnOpening()
        {
            base.OnOpening();

            if(Description!=null)
            {
                
                foreach (ServiceEndpoint t in Description.Endpoints)
                    if(!t.Behaviors.Any(b=>b is DispatchMessageInspector))
                        t.Behaviors.Add(new DispatchMessageInspector(ServiceBehaviorExtension));
             
                
            }
        }
    }
}
